const lazyLoadImage = defaultImage => {
	let windowHeight = document.documentElement.clientHeight || document.body.clientHeight //可视区域高

	function throttle(fn, delay) { //节流
		let timeout = null
		return (...args) => {
			if (timeout) return
			timeout = setTimeout(() => {
				fn.apply(this, args)
				timeout = null
			}, delay);
		}

	}

	function loadImage(el) { //加载图片
		return () => {
			let top = el.getBoundingClientRect().top
			let bottom = el.getBoundingClientRect().bottom
			if (top - windowHeight < 0 && bottom > 0 && el.hasAttribute('data-src')) { //图片出现在可视区域内开始加载图片
				el.src = el.getAttribute('data-src')
				el.removeAttribute('data-src')

			}
		}
	}

	return {
		bind(el, binding) {
			el.src = defaultImage
			el.setAttribute('data-src', binding.value)
		},
		inserted(el) {
			loadImage(el)() //显示初始（首屏）图片
			window.addEventListener('scroll', throttle(loadImage(el), 500)) //每滚动500毫秒加载一次图片
		}

	}
}


const install = {
	install(vue, defaultImage) {
		//v-lazy
		vue.directive('lazy', lazyLoadImage(defaultImage))
	}
}

export default install